import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {PagesService} from "../../services/pages.service";
import {Setting} from "../../public/setting/setting";

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  public validateForm: FormGroup = this.fb.group({
    account: [null, [Validators.required]],
    password: [null, Validators.compose([Validators.required])]
  });//登录的表单

  constructor(private fb: FormBuilder,
              public navCtrl: NavController,
              public navParams: NavParams,
              private pagesService: PagesService
  ) {
    let token = localStorage.getItem(Setting.storage.authorizationToken);
    if (token) this.navCtrl.setRoot('HomePage');//如果有token，跳转到首页
  }

  ionViewDidLoad() {
  }

  /**
   * 登录
   * @param $event
   * @param value
   */
  login($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    // login
    me.pagesService.login(me.validateForm.value).then((data: string) => {
      me.navCtrl.setRoot('HomePage');
      localStorage.setItem(Setting.storage.authorizationToken, data);//验证token存入本地
    })
  };

  /**
   * from表单
   * @param name
   * @returns {AbstractControl}
   */
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
